Team Performance

Row

Goal Differential Over Time

Differential Distribution

Row

Assists Origin

Assists Origin

Assist Types

Type n
Assist Types
Short Pass 5
Cross In 3
Long Through Ball 2
Chip 1
Though Ball 1
Assist Locations
Inside the Box 4
Close to Byline 3
Own Half 2
Midfield 1
Outside the Box 1
Top Box 1

Row

Goals Origin

Goal Types

Type n
Shot Types
Direct Shot 13
Dribble 2
Tap In 2
Free Kick 1
Penalty Kick 1
Shot Locations
Inside the Box 14
Outside the Box 4
6 Yard Box 1

Field Type Effect

Venue Games For Against
Artificial 4 16 4
Natural 2 3 2

Individual Performance

Row

Player Assists Goals Goals + Assists
Pablo 2 8 10
Artur 1 4 5
Pedro 3 2 5
Colton 1 1 2
Justin 2 0 2
Dalton 0 1 1
Denis 0 1 1
Devin 0 1 1
Hugh 0 1 1
Alex 1 0 1
Ed 1 0 1
Hermone 1 0 1

Row

# A tibble: 9 × 4
  Assister total_assist Scorer person_assists
  <chr>           <int> <chr>           <int>
1 Pedro               3 Pablo               3
2 Justin              2 Colton              1
3 Justin              2 Denis               1
4 Pablo               2 Pedro               2
5 Alex                1 Pablo               1
6 Artur               1 Pablo               1
7 Colton              1 Pablo               1
8 Ed                  1 Dalton              1
9 Hermone             1 Artur               1
# A tibble: 8 × 2
  new_column        total
  <chr>             <int>
1 Pablo and Pedro       5
2 Alex and Pablo        1
3 Artur and Hermone     1
4 Artur and Pablo       1
5 Colton and Justin     1
6 Colton and Pablo      1
7 Dalton and Ed         1
8 Denis and Justin      1
# A tibble: 4 × 2
  Scorer     n
  <chr>  <int>
1 Artur      3
2 Pablo      2
3 Devin      1
4 Hugh       1
---
title: "MRSL D2 Knights 2023"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    social: menu
    source_code: embed
---

<!--------------------------------------------------------------------------------------
                                  SET UP: PACKAGES, FUCNTIONS, DATA LAOD 
------------------------------------------------------------------------------------> 

```{r}
knitr::opts_chunk$set(
  echo = F, warning = F, message = F
)
```

```{r packages }

library(ggthemes, quietly = TRUE)
library(htmltools, quietly = TRUE)
library(tidyverse)
library(plotly)
library(flexdashboard)
library(ggsoccer)
library(googleAuthR)
library(googlesheets4)
library(kableExtra)
library(shinydashboard)
library(scales)

```

```{r}
int_breaks <- function(x, n = 5) {
  l <- pretty(x, n)
  l[abs(l %% 1) < .Machine$double.eps ^ 0.5] 
}
```

```{r laod goals and assists data}

scores <- 
  read_sheet("https://docs.google.com/spreadsheets/d/1xy6CVRLfpO2tsVxcl5ZlwOGvqqlTipfcC4T4YBgM8ZY/edit#gid=0", 
             sheet = "Knights")

scores$Group <- 
  with(scores, 
       case_when(
         `Player Position` %in% c("LW", "RW", "ST") ~ "Attackers", 
         `Player Position` %in% c("CM") ~ "Midfielders", 
         T ~ "Defenders"
       ))

scores$Group <- factor(scores$Group, levels = c("Defenders", "Midfielders", "Attackers"))

```

```{R load schedule and resutls data}
schedule <- 
  read_sheet("https://docs.google.com/spreadsheets/d/1xy6CVRLfpO2tsVxcl5ZlwOGvqqlTipfcC4T4YBgM8ZY/edit#gid=0", 
             sheet = "Schedule")

schedule <- 
  schedule %>% 
  filter(Division == "D2" & !is.na(`Final Score` )) %>% 
  mutate(
    game = seq(from = 1, to = nrow(.), by = 1)
  )

schedule$`Home Score` = with(schedule, substr(`Final Score`, 2, 2))
schedule$`Home Score` <- as.numeric(schedule$`Home Score`)

schedule$`Away Score` = with(schedule, substr(`Final Score`, 4, 4))
schedule$`Away Score` <- as.numeric(schedule$`Away Score`)

schedule$our_goals = 
  with(schedule, 
       case_when(
         Home == "Knights" ~ `Home Score`, 
         T ~ `Away Score`
       ))
schedule$our_conceded = 
  with(schedule, 
       case_when(
         Home == "Knights" ~ `Away Score`, 
         T ~ `Home Score`
       ))

schedule$opponent = 
  with(schedule, 
       case_when(
         Home == "Knights" ~ Away, 
         T ~ Home
       ))

```

<!--------------------------------------------------------------------------------------
                                            DASHBOARD BODY
------------------------------------------------------------------------------------> 
Team Performance {.tabset }
===

Row {data-height=1600}
---

### Goal Differential Over Time {data-width=1000}

```{r differential over timeline }

schedule %>% 
  mutate(
    goals_for = cumsum(our_goals), 
    goals_against = cumsum(our_conceded), 
    
    differential = goals_for - goals_against
  ) %>% 
  select(game, Date, goals_for, goals_against, differential, opponent) %>% 
  
  pivot_longer(
    cols = c("goals_for", "goals_against"), 
    values_to = "Val", 
    names_to = "Type"
  ) %>% 
  
  mutate(
    Type = case_when(
      Type == "goals_for" ~ "Goals Scored", 
      T ~ "Goals Conceded"
    )
  ) -> plot_df

plot_df %>% 
  plot_ly(
    x = ~game,
    y = ~Val,
    color = ~Type,
    colors = c("red", "#36c959"),
    
    type = "scatter",
    mode = "lines+markers", 
    
    text = 
      with(. , 
           paste(
             "Date: ", Date, 
             "<br>Opponent: ", opponent, 
             "<br>Goals:", Val, 
             "<br>Type: ", Type, 
             "<br>Differential", differential
    )), 
    
    hoverinfo = "text"
  ) %>% 
  layout(
    yaxis = list(
      range = c(0, max(cumsum(schedule$our_goals)) + 1), 
      title = "Goals For and Against"
    ), 
    xaxis = list(
      title = "Game #"
    ), 
    legend = list(
      orientation = "h", y = -.2
      )
    )


```

### Differential Distribution {data-width=1000}

```{r}

schedule %>% 
  mutate(
    differential = our_goals - our_conceded
  ) -> schedule

schedule %>% 
  ggplot(aes(x = differential)) + 
  geom_histogram(
    binwidth = 1, 
    color = "grey", 
    fill = "blue"
    ) + 
  
  scale_x_continuous(
    labels = seq(from = min(schedule$differential), 
                 to =  max(schedule$differential), 
                 by = 1),
    
    breaks = seq(from = min(schedule$differential), 
                 to =  max(schedule$differential), 
                 by = 1)
  ) + 
  
  scale_y_continuous(
    breaks = function(x) int_breaks(x, n = 10)
  ) + 
  
  theme_minimal() + 
  
  xlab("Goal Differential") + 
  ylab("Count") + 
  
  ggtitle(
    paste("Average per Game:", 
          round(mean(schedule$differential), 4))
  )

```

Row {data-height=1600}
---

### Assists Origin 

```{r}
scores %>% 
  filter(Action == "Assist") %>% 
  group_by(`Field Part`) %>% 
  summarize(n = n(), 
            p = n()/nrow(.)) -> 
  
  assists

assists <- assists %>% arrange(`Field Part`)

assists$y_lab = c(85,50,15)
assists$x_lab = c(75,75,75)

assists$label = with(assists, paste0(n, " (", round(p, 4)*100, "%)"
                                     )
                     )


ggplot(data = assists, 
       aes(x = x_lab, y = y_lab, label = label)) +
  annotate_pitch(colour = "#999e9b") +
  theme_pitch(aspect_ratio = NULL) + 
  geom_point(color = "white") + 
  geom_text(size=7.5) + 
  
  geom_segment(
    x = 30, xend = 89, 
    y = 67, yend = 67,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    arrow = arrow(length = unit(0.3, "inches")),
    colour = "blue" # Also accepts "red", "blue' etc
  )+ 
  
  geom_segment(
    x = 30, xend = 89, 
    y = 33, yend = 33,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    arrow = arrow(length = unit(0.3, "inches")),
    colour = "blue" # Also accepts "red", "blue' etc
  )
```

### Assists Origin 

```{r}
scores %>% 
  filter(Action == "Assist") %>% 
  group_by(`Group`) %>% 
  summarize(n = n(), 
            p = n()/nrow(.)) -> 
  
  assists2

assists2 <- assists2 %>% arrange(`Group`)

assists2$y_lab = c(25,50,75)
assists2$x_lab = c(15,50,85)

assists2$label = with(assists2, paste0(n, " (", round(p, 4)*100, "%)"
                                     )
                     )


ggplot(data = assists2, 
       aes(x = x_lab, y = y_lab, label = label)) +
  annotate_pitch(colour = "#999e9b") +
  theme_pitch(aspect_ratio = NULL) + 
  geom_point(color = "white") + 
  geom_text(size=7.5) + 
  
  geom_segment(
    x = 67, xend = 67, 
    y = 10, yend = 90,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    colour = "red" # Also accepts "red", "blue' etc
  )+ 
  
  geom_segment(
    x = 31, xend = 31, 
    y = 10, yend = 90,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    colour = "red" # Also accepts "red", "blue' etc
  ) + 
  
  geom_segment(
    x = 15, xend = 25, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  ) + 
  
  geom_segment(
    x = 45, xend = 55, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  )+ 
  
  geom_segment(
    x = 75, xend = 85, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  )
```

### Assist Types

```{r}

scores %>% 
  filter(Action == "Assist") %>% 
  group_by(`Pass Type`) %>% 
  summarise(n = n()) %>% 
  arrange(-n) %>% 
  rename(
    Type = `Pass Type`
  ) -> pass_types

n_shot_types <- nrow(pass_types)

scores %>% 
  filter(Action == "Assist") %>% 
  group_by(`Position`) %>% 
  summarise(n = n()) %>% 
  arrange(-n) %>% 
  rename(
    Type = `Position`
  ) -> pass_loc

n_shot_loc <- nrow(pass_loc)

shot_sum <- rbind(pass_types, pass_loc)

shot_sum %>% 
  kable(align = 'l') %>% 
  kable_styling(bootstrap_options = c("condesed", "striped")) %>% 
  pack_rows("Assist Types", 1, n_shot_types) %>%
  pack_rows("Assist Locations", (n_shot_types+1), (n_shot_loc + n_shot_types))

```

Row
---

### Goals Origin 

```{r}

scores %>% 
  filter(Action == "Goal") %>% 
  group_by(`Group`) %>% 
  summarize(n = n(), 
            p = n()/nrow(.)) -> 
  
  goals

goals <- goals %>% arrange(`Group`)

goals$y_lab = c(50,75)
goals$x_lab = c(50,85)

goals$label = with(goals, paste0(n, " (", round(p, 4)*100, "%)"
                                     )
                     )


ggplot(data = goals, 
       aes(x = x_lab, y = y_lab, label = label)) +
  annotate_pitch(colour = "#999e9b") +
  theme_pitch(aspect_ratio = NULL) + 
  geom_point(color = "white") + 
  geom_text(size=7.5) + 
  
  geom_segment(
    x = 67, xend = 67, 
    y = 10, yend = 90,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    colour = "red" # Also accepts "red", "blue' etc
  )+ 
  
  geom_segment(
    x = 31, xend = 31, 
    y = 10, yend = 90,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    linetype = "dashed", 
    size = 2, 
    colour = "red" # Also accepts "red", "blue' etc
  ) + 
  
  geom_segment(
    x = 15, xend = 25, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  ) + 
  
  geom_segment(
    x = 45, xend = 55, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  )+ 
  
  geom_segment(
    x = 75, xend = 85, 
    y = 85, yend = 85,
    lineend = "round", # See available arrow types in example above
    linejoin = "round",
    size = 1, 
    arrow = arrow(length = unit(0.1, "inches")),
    colour = "#7fb550" # Also accepts "red", "blue' etc
  )
```

### Goal Types

```{r}

scores %>% 
  filter(Action == "Goal") %>% 
  group_by(`Shot Type`) %>% 
  summarise(n = n()) %>% 
  arrange(-n) %>% 
  rename(
    Type = `Shot Type`
  ) -> shot_types

n_shot_types <- nrow(shot_types)

scores %>% 
  filter(Action == "Goal") %>% 
  group_by(`Position`) %>% 
  summarise(n = n()) %>% 
  arrange(-n) %>% 
  rename(
    Type = `Position`
  ) -> shot_loc

n_shot_loc <- nrow(shot_loc)

shot_sum <- rbind(shot_types, shot_loc)

shot_sum %>% 
  kable(align = 'l') %>% 
  kable_styling(bootstrap_options = c("condesed", "striped")) %>% 
  pack_rows("Shot Types", 1, n_shot_types) %>%
  pack_rows("Shot Locations", (n_shot_types+1), (n_shot_loc + n_shot_types))


```


### Field Type Effect

```{r}

schedule %>% 
  group_by(
    Venue
  ) %>% 
  summarise(
    Games = n(), 
    For = sum(our_goals), 
    Against = sum(our_conceded)
  ) %>% 
  
  kable(align = c('l', 'c', 'c', 'c')) %>% 
  kable_styling(
    bootstrap_options = c("condensed", "striped")
  )

```

Individual Performance
===

Row
---

```{r}

scores %>% 
  filter(Action == "Assist") %>% 
  group_by(Player) %>% 
  summarise(Assists = n()) %>% 
  arrange(-Assists) -> ast

```

```{r}

scores %>% 
  filter(Action == "Goal") %>% 
  group_by(Player) %>% 
  summarise(Goals = n()) %>% 
  arrange(-Goals) -> gls

```

```{R}

merge(ast, gls, all = T, by = "Player") -> all_

all_$Assists <- ifelse(is.na(all_$Assists), 0, all_$Assists)
all_$Goals <- ifelse(is.na(all_$Goals), 0, all_$Goals)
all_$`Goals + Assists` <- all_$Assists + all_$Goals

all_ <- all_ %>% arrange(-`Goals + Assists`, -Goals, -Assists, Player)

all_ %>% 
  kable(align = 'c') %>% 
  kable_styling(bootstrap_options = c("striped", "condensed"))
```

Row
---

```{r}

linkups <- 
  scores %>% filter(Action == "Goal") %>% 
    select(Date, Opponent, Score, Player, `Player Position`, `Play Type`) %>% 
    rename(Scorer = Player) %>% 
  
  left_join(
    scores %>% filter(Action == "Assist") %>% 
      select(Date, Opponent, Score, Player) %>% 
      rename(Assister = Player), 
    
    by = c("Date", "Opponent", "Score")
  )

linkups %>% 
  group_by(Assister) %>% 
  summarise(total_assist = n()) %>% 
  filter(!is.na(Assister)) %>% 
  
  left_join(
    linkups %>% 
      group_by(
        Assister, Scorer
      ) %>% 
      summarise(
        person_assists = n()
      ), 
    
    by = "Assister"
  ) %>% 
  
  arrange(-total_assist , Assister) -> advanced_assist_tally

advanced_assist_tally
```

```{r}

advanced_assist_tally %>% 
  rowwise() %>%
  mutate(new_column = paste(sort(unique(c(Assister, Scorer))), collapse = " and ")) %>% 
  group_by(new_column) %>% 
  summarise(total = sum(person_assists)) %>% 
  arrange(-total)  

```

```{R}

assistless <- 
  linkups %>% filter(is.na(Assister) ) %>% 
  group_by(
    Scorer
  ) %>% 
  summarize(n = n()) %>% 
  arrange(-n)
  
assistless
```